package simulation;

import gui.MainGUI;
import houseHold.House;

import java.util.Iterator;
import java.util.Set;

import person.PersonAchive;
import sensor.Sensor;
import timer.Timer;
import constants.Constants;
import db.DBConnection;

public class DataCollector implements Runnable {
	private static int time = 0;

	private void collectAllData() {
		time += Constants.time;
		if (time < 86400) {
			double value = (double) time / (double) Timer.getMaxTime();
			value = value * 100;
			System.out.println("VALUE = " + value);
			if (time == Timer.getMaxTime())
				return;
			MainGUI.getInstance().setProgressBarValue((int) value);
			for (int r = 0; r < House.getInstance().getRoomCount(); r++) {
				Set<String> keySet = House.getInstance().getRoom(r)
						.getSensors().keySet();
				Iterator<String> it = keySet.iterator();
				while (it.hasNext()) {
					String current = it.next();
					Sensor currSens = House.getInstance().getRoom(r).getSensor(
							current);
					DBConnection.insertData(date + " " + transformTime(),
							currSens.getSensorData(House.getInstance().getRoom(
									r), time), currSens.getSensorName());
					/*
					 * System.out.println(transformTime() + " " +
					 * currSens.getSensorName() + " " + currSens.getSensorData(
					 * House.getInstance().getRoom(r), time));
					 */
				}
			}

			for (int i = 0; i < PersonAchive.getCount(); i++) {
				Sensor currSens = PersonAchive.getPerson(i).getrFid();
				DBConnection.insertData(date + " " + transformTime(), currSens
						.getSensorData(null, time), currSens.getSensorName());
				/*
				 * System.out.println(transformTime() + " " +
				 * currSens.getSensorName() + " " + currSens.getSensorData(
				 * null, time));
				 */
			}

		}
	}

	public void run() {
		DBConnection.readyInserts();
		time = 0;
		while (true) {
			while (ScheduleProgram.masterAcess() != true
					&& ScheduleProgram.masterFinish() != true) {

				try {
					Thread.sleep(10);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (ScheduleProgram.masterFinish() == true) {
				// MainGUI.setSimulationStatus(Constants.green,
				// "Simulation finished");
				break;
			}
			collectAllData();
			ScheduleProgram.activateAll();
		}
		System.out.println("finished DC");
		DBConnection.closeInserts();
		return;
	}

	private String date = new String();

	public DataCollector(String date) {
		this.date = date;
	}

	private String transformTime() {
		int hours = 0, minutes = 0, seconds = 0;
		String timeStr = new String();
		hours = (time / 3600);
		minutes = (time - hours * 3600) / 60;
		seconds = time - hours * 3600 - minutes * 60;
		timeStr = hours + ":" + minutes + ":" + seconds;
		return timeStr;
	}

}
